package com.xrh.xdemo.service.controllers;

import java.awt.Color;
import java.awt.Font;
import java.awt.image.BufferedImage;
import java.net.URLDecoder;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.xrh.core.bean.CommonResult;
import com.xrh.core.dto.UploadFileInfoDTO;
import com.xrh.core.enums.ResultCodeEnum;
import com.xrh.core.exceptions.BusinessException;
import com.xrh.core.interfaces.FileUtilsInf;
import com.xrh.core.utils.XAssert;

import cn.hutool.core.img.ImgUtil;
import cn.hutool.extra.spring.SpringUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

@Api(tags = "文件API")
@RestController
@RequestMapping("/file")
@Slf4j
public class FileController {

    @Resource
    HttpServletRequest request;
    
    @Resource
    HttpServletResponse response;
    
	 /**
   	 * @function 下载文字图片
   	 * @author 肖荣辉
   	 * @date 2022-09-02 15:07:07
   	*/
   	@ApiOperation("下载文字图片")
    @GetMapping(value ="/downLoadWordPng")
   	public  void downLoadWordPng(){
   		
  		try {
  			
  			String word = "【"+request.getParameter("word")+"】";
  			
  			word = URLDecoder.decode(word , "gbk");
  			
  			Font font = new Font("宋体", Font.BOLD, 12);
  			
  			BufferedImage bufferedImage = ImgUtil.createImage(word , font, Color.WHITE, Color.BLACK, BufferedImage.TYPE_INT_RGB);
  			
  			ImgUtil.writePng(bufferedImage, response.getOutputStream());
   			
   		}  catch (Exception e) {
   			log.error("downLoadWordPng 发生错误 ==> " , e);
   		}
   		
   	}
   	
    /**
     * @function 上传文件
     * @author 肖荣辉
     * @date 2021年8月27日
     */
    @ApiOperation(value="上传文件")
    @PostMapping("/uploadFile")
    public CommonResult<UploadFileInfoDTO> uploadFile (@RequestParam("file") MultipartFile file){
    	try {
    		
    	    FileUtilsInf fileUtilsInf = SpringUtil.getBean(FileUtilsInf.class);
    		
    		XAssert.isTrue(fileUtilsInf != null, "暂不支持文件上传 , 请先安装好minio以及配置好配置文件");
    		
    		return CommonResult.success(fileUtilsInf.upload(file));
    		
    	} catch (BusinessException e) {
    		return  CommonResult.failed(e.getCode() , e.getMsg());
    	} catch (Exception e) {
    		log.error("uploadFile 发生错误 ==> " , e);
    		return CommonResult.failed(ResultCodeEnum.SYSTEM_FAILED);
    	}
    	
    }

}
